package com.authine.cloudpivot.common.extension.customized;

import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.common.extension.customized.model.User;
import com.authine.cloudpivot.common.extension.customized.service.CustomizedTestServiceI;
import com.authine.cloudpivot.common.organization.feign.OrganizationFeignService;
import com.authine.cloudpivot.common.organization.model.Department;
import com.authine.cloudpivot.common.organization.model.Organization;
import com.authine.common.json.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import javax.swing.plaf.IconUIResource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 二开扩展demo
 */
@Api(tags = "公共服务二开扩展服务::二开API")
@Slf4j
@RequestMapping("/customized")
@RestController
public class CustomizedTestController {

    @Autowired
    private CustomizedTestServiceI customizedTestServiceI;

    @Autowired
    private OrganizationFeignService organizationFeignService;

    @GetMapping("/setDeptSortKey")
    public SingleResponse setDeptSortKey(){
        int num=0;
        MultiResponse<Organization> organizations = organizationFeignService.listOrganization();
        organizations.getData().stream().forEach(o-> {
            MultiResponse orgIdsRsp = organizationFeignService.getAllChildDeptIds(Collections.singletonList(o.getDepartmentId()));
            if(orgIdsRsp.getData().size()>1){
             SingleResponse<Department> dptRsp = organizationFeignService.getDepartment(o.getDepartmentId());
             Department department = dptRsp.getData();
             department.setSortKey(2);
             organizationFeignService.updateDepartment(department);
            }
        });
        return SingleResponse.buildSuccess();
    }
    @ApiOperation("组织数据")
    @GetMapping("/setOrg")
    public SingleResponse setOrg(){
        StringBuilder deptStr = new StringBuilder();
        StringBuilder userStr = new StringBuilder();
      MultiResponse<Organization> organizations = organizationFeignService.listOrganization();
      organizations.getData().stream().forEach(o->{
          MultiResponse orgIdsRsp = organizationFeignService.getAllChildDeptIds(Collections.singletonList(o.getDepartmentId()));
          System.out.println("--获取所有子部门id--");
          System.out.println(orgIdsRsp.getData());
       List<String> result= (List<String>) orgIdsRsp.getData().stream().map(item->{
             return String.format("'%s'",item);
          }).collect(Collectors.toList());
          //更新部门
          String updateDeptSql = getUpdateDeptSql(result,o.getId());
          Integer num=  executeUpdate(updateDeptSql);
          deptStr.append(num).append("->");
          //更新用户
          String updateUserSql = getUpdateUserSql(result,o.getId());
          Integer userNum = executeUpdate(updateUserSql);
          userStr.append(userNum).append("=>");

      });

      return SingleResponse.of(deptStr.append("/n").append(userStr.toString()).toString());
    }

    @Autowired
    DataSource dataSource;

    public final String getUpdateDeptSql(List<String> departIds,String orgId){
       return String.format("update h_org_department set org_id=%s where id in (%s)",orgId, StringUtils.join(departIds,","));
    }

    public final String getUpdateUserSql(List<String> deptIds,String orgId){
        return String.format("update h_org_user set org_id=%s where main_department_id in (%s)",orgId,StringUtils.join(deptIds,","));
    }
    public int executeUpdate(String sql) {
        Connection con = null;
        int count = 0;
        try {
            con = dataSource.getConnection();
            Statement statement = con.createStatement();
            System.out.println(sql);
            count= statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       return count;
    }
    @ApiOperation("测试API")
    @GetMapping("/test1")
    public SingleResponse<User> test1() {
        User user = new User();
        user.setName("哈哈");
        user.setAge(26);
        user.setBirthday(new Date());
        return SingleResponse.of(user);
    }

    @ApiOperation("测试调用Service")
    @GetMapping("/test2")
    public MultiResponse<String> test2() {
        List<String> names = customizedTestServiceI.listName();
        return MultiResponse.ofWithoutTotal(names);
    }

    @ApiOperation("用户列表")
    @GetMapping("/user/list")
    public MultiResponse<User> list() {
        List<User> users = customizedTestServiceI.list();
        return MultiResponse.ofWithoutTotal(users);
    }

    @ApiOperation("新增用户")
    @PostMapping("/user")
    public SingleResponse<User> create(@RequestBody User user) {
        if (user == null) {
            return SingleResponse.of(null);
        }
        customizedTestServiceI.create(user);
        return SingleResponse.of(user);
    }

    @ApiOperation("更新用户")
    @PutMapping("/user")
    public SingleResponse<User> update(@RequestBody User user) {
        if (user == null) {
            return SingleResponse.of(null);
        }
        customizedTestServiceI.update(user);
        return SingleResponse.of(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/user/{id}")
    public SingleResponse<Integer> delete(@PathVariable("id") String id) {
        int result = customizedTestServiceI.delete(id);
        return SingleResponse.of(result);
    }

}

